package off_imp

import (
	sqlc "bp/db/sqlc"
	"bp/internal/render"
	"bp/internal/service/com/offer"
	"bp/internal/util"
	offGrpc "bp/rpc/gen/backendapi/off"
	"context"
)

// // 交易锁定(正向)
func (s *OffBackendApiImp) LockTransaction(ctx context.Context, req *offGrpc.LockTransactionReq) (res *offGrpc.LockTransactionRes, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("off_imp/query.LockTransaction=>%+v", req)
	defer render.FriendlyEntityError(&err, EntityName)
	res = &offGrpc.LockTransactionRes{}

	var off int32
	var offTransactionOrderPtrs []*offer.OffTransactionOrder
	var transactionIDs []int64
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {
		toLockTransactOrderPtrs, err := s.VldLockTransactionReq(ctx, q, req)
		if err != nil {
			return
		}
		off, offTransactionOrderPtrs, transactionIDs, err = s.comHub.OfferService.LockTransaction(ctx, q, &offer.LockTransactionParam{
			BrandID:       req.BrandId,
			MemberID:      req.MemberId,
			OutTransNo:    req.OutTransNo,
			TransactScene: req.TransactScene,
			OrderPtrs:     toLockTransactOrderPtrs,
		})
		if err != nil {
			return
		}
		slog.Infof("优惠试算 ok")
		return
	})
	if err != nil {
		return
	}

	go s.AsyncApportionOff(ctx, transactionIDs)
	// ch := s.comHub.ApportionService.GetApportionWorker()

	res.Off = off
	res.Orders = s.ConvOffTransactOrderPtrArrayEntityToPb()(offTransactionOrderPtrs)
	return
}
